import React from 'react';

interface IProps {
  className?: string;
  titleClassName?: string;
  defaultChecked?: boolean;
  title?: string;
  onToggle?: (checked: boolean) => void;
  onRef?: (ref: React.Component) => void;
}
export default class Checkbox extends React.Component<IProps, any> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      checked: props.defaultChecked || false,
    };
    this.onToggle = this.onToggle.bind(this);
  }

  public componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  public onToggle() {
    if (this.props.onToggle) {
      this.props.onToggle(!this.state.checked);
    }
    this.setState({
      checked: !this.state.checked,
    });
  }

  public check() {
    this.setState({
      checked: true,
    });
  }

  public cancelCheck() {
    this.setState({
      checked: false,
    });
  }

  public render() {
    let classString = '';
    const className = this.props.className || '';
    if (this.state.checked) {
      classString = `bricks-checkbox checked ${className}`;
    } else {
      classString = `bricks-checkbox ${className}`;
    }

    return (
      <div className={classString} onClick={this.onToggle}>
        <span className="checkbox-icon">{this.props.children}</span>
        <span className={this.props.titleClassName || ''}>{this.props.title || ''}</span>
      </div>
    );
  }
}
